package com.flux.controller;

import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuples;

import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by Robo on 2018/4/8.
 */
@RestController
@RequestMapping("/sse")
public class SseController {

    @GetMapping("/random")
    public Flux<ServerSentEvent<Integer>> randomNumber(){
        Integer count = 0;
        return Flux.interval(Duration.ofSeconds(1))
                .map(seq -> {
                    int random = ThreadLocalRandom.current().nextInt();
                    return Tuples.of(seq, random, seq + Math.abs(random));
                })
                .map(data -> ServerSentEvent.<Integer>builder().event("random" + data.getT3())
                        .id(Long.toString(data.getT1())).data(data.getT2()).build());
    }
}
